import java.io.File;

import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

public class FileDropTargetListener implements DropTargetListener {

	private FileUploadUI fileUploadUI;

	public FileDropTargetListener(FileUploadUI fileUploadUI) {
		this.fileUploadUI = fileUploadUI;
	}

	public void dragEnter(DropTargetEvent event) {
		if (event.detail == DND.DROP_DEFAULT) {
			if ((event.operations & DND.DROP_COPY) != 0) {
				event.detail = DND.DROP_COPY;
			} else {
				event.detail = DND.DROP_NONE;
			}
		}
		if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
			if (event.detail != DND.DROP_COPY) {
				event.detail = DND.DROP_NONE;
			}
		}
	}

	public void dragLeave(DropTargetEvent event) {
	}

	public void dragOperationChanged(DropTargetEvent event) {
		if (event.detail == DND.DROP_DEFAULT) {
			if ((event.operations & DND.DROP_COPY) != 0) {
				event.detail = DND.DROP_COPY;
			} else {
				event.detail = DND.DROP_NONE;
			}
		}
		if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
			if (event.detail != DND.DROP_COPY) {
				event.detail = DND.DROP_NONE;
			}
		}
	}

	public void dragOver(DropTargetEvent event) {
	}

	public void drop(DropTargetEvent event) {
		if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
			String[] files = (String[]) event.data;
			for (int i = 0, len = files.length; i < len; i++) {
				String url = files[i];
				if(url!=null){
                	File file = new File(url);
                	if(file.exists()){
                		TableItem newItemTableItem = new TableItem(fileUploadUI.getUploadFileTable(), SWT.BORDER);
                		fileUploadUI.sendFile(file, newItemTableItem);
                	}
                }
			}
		}
	}

	public void dropAccept(DropTargetEvent event) {
	}

}
